package csc.daonjpa.java.controller;

import java.util.List;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import csc.daonjpa.java.domain.Card;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.service.BankService;

@Controller
public class CardController {

	private static final Logger LOG = Logger.getLogger(CardController.class);
	private BankService bankService;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	/**
	 * Add a card to DB
	 */
	@RequestMapping(value = "/createCard", method = RequestMethod.POST)
	public String addCard(HttpServletRequest request, Model model) {

		// Read card info from request and save into card object
		String cardType = request.getParameter("cardType");
		String cardBank = request.getParameter("cardBank");
		Customer currentCustomer = (Customer) request.getSession()
				.getAttribute("currentCustomer");

		// Test if there is an existing card with same bank and type
		Card existCard = bankService.getCardByTypeAndName(cardBank, cardType);

		if (existCard != null) {
			model.addAttribute("errorMessage",
					"You've already had a card with this type and this bank!");
		} else {
			// Bi-directional
			Card card = new Card(cardType, cardBank);

			currentCustomer.addCard(card);
			card.setCustomer(currentCustomer);

			try {
				// Save card to DB
				bankService.addCard(card);
				model.addAttribute("successMessage",
						"Added new card successfully");
			} catch (PersistenceException ex) {
				if (ex.getCause() instanceof ConstraintViolationException) {
					model.addAttribute("errorMessage", "Duplicated card found");
				} else {
					model.addAttribute("errorMessage", "Error adding new card");
				}
				LOG.error("Error found adding an card", ex);
				throw ex;
			} catch (Exception e) {
				LOG.error("General Error found adding an card", e);
				throw e;
			}
		}
		return "forward:/listCards";
	}

	@RequestMapping(value = "/listCards")
	public ModelAndView getCardList(HttpServletRequest request, Model model) {

		// Get the customer loginid
		Customer currentCustomer = (Customer) request.getSession()
				.getAttribute("currentCustomer");
		String custLoginId = currentCustomer.getLoginid();

		// Get the list of all cards from DB
		List<Card> cards = bankService.getCardsByCustomerId(custLoginId);

		ModelAndView modelAndView = new ModelAndView("cardList");
		modelAndView.addObject("listCard", cards);
		return modelAndView;
	}

	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {

		ModelAndView model = new ModelAndView("cardList");
		model.addObject("errorMessage", "Exception occurred");

		return model;
	}
}
